"use client"

import React, { useEffect } from "react"
import { Form, Input, Select, Upload, Button, Space, Switch, message } from "antd"
import { UploadOutlined } from "@ant-design/icons"
import type { Host } from "../types"
import { HOST_TYPE_NAMES } from "../types"

interface HostFormProps {
  initialValues?: Host
  categories: string[]
  onSubmit: (values: Host) => void
  onCancel: () => void
}

export const HostForm: React.FC<HostFormProps> = ({ initialValues, categories, onSubmit, onCancel }) => {
  const [form] = Form.useForm()
  const [isComment, setIsComment] = React.useState(initialValues?.isComment || false)

  useEffect(() => {
    if (initialValues) {
      form.setFieldsValue(initialValues)
      setIsComment(initialValues.isComment || false)
    }
  }, [initialValues, form])

  const handleSubmit = async (values: any) => {
    try {
      const hostData: Host = {
        ...values,
        id: initialValues?.id || Date.now().toString(),
        lastUpdated: new Date().toISOString(),
        isComment: isComment,
        hostContent: isComment ? values.commentText : `${values.ip} ${values.domain}`,
      }

      onSubmit(hostData)
      form.resetFields()
    } catch (error) {
      message.error("提交失败")
    }
  }

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={{
        type: "other",
        ...initialValues,
      }}
    >
      <Form.Item label="是否为注释" name="isComment" valuePropName="checked">
        <Switch onChange={(checked) => setIsComment(checked)} checkedChildren="是" unCheckedChildren="否" />
      </Form.Item>

      {isComment ? (
        <Form.Item name="commentText" label="注释内容" rules={[{ required: true, message: "请输入注释内容" }]}>
          <Input.TextArea rows={4} />
        </Form.Item>
      ) : (
        <>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入标题" }]}>
            <Input />
          </Form.Item>

          <Space style={{ width: "100%" }} size="middle">
            <Form.Item
              name="ip"
              label="IP 地址"
              rules={[
                { required: true, message: "请输入 IP 地址" },
                {
                  pattern: /^(\d{1,3}\.){3}\d{1,3}$/,
                  message: "请输入有效的 IP 地址",
                },
              ]}
              style={{ flex: 1 }}
            >
              <Input placeholder="127.0.0.1" />
            </Form.Item>

            <Form.Item
              name="domain"
              label="域名"
              rules={[{ required: true, message: "请输入域名" }]}
              style={{ flex: 1 }}
            >
              <Input placeholder="example.com" />
            </Form.Item>
          </Space>

          <Space style={{ width: "100%" }} size="middle">
            <Form.Item name="type" label="类型" rules={[{ required: true, message: "请选择类型" }]} style={{ flex: 1 }}>
              <Select>
                {Object.entries(HOST_TYPE_NAMES).map(([key, value]) => (
                  <Select.Option key={key} value={key}>
                    {value}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="category"
              label="分类"
              rules={[{ required: true, message: "请选择分类" }]}
              style={{ flex: 1 }}
            >
              <Select showSearch allowClear placeholder="选择或输入分类">
                {categories.map((category) => (
                  <Select.Option key={category} value={category}>
                    {category}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Space>

          <Form.Item name="description" label="描述">
            <Input.TextArea rows={4} />
          </Form.Item>

          <Form.Item name="image" label="图标">
            <Upload
              maxCount={1}
              listType="picture"
              beforeUpload={(file) => {
                const reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = () => {
                  form.setFieldsValue({
                    image: reader.result,
                  })
                }
                return false
              }}
            >
              <Button icon={<UploadOutlined />}>上传图标</Button>
            </Upload>
          </Form.Item>

          <Form.Item name="color" label="颜色">
            <Input type="color" style={{ width: 60 }} />
          </Form.Item>
        </>
      )}

      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            {initialValues ? "更新" : "添加"}
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      </Form.Item>
    </Form>
  )
}
